package pers.course.test;

public class StringBenchMark {
    public static void main(String[] args) {
        /*
        String创建
         */
        long beginTime, elapsedTime;
        String str = "";
        int size = 16536;
        char ch = 'a';
        beginTime = System.nanoTime();
        for (int count = 0; count < size; ++count) {
            str += ch;
            ++ch;
            if (ch > 'z') {
                ch = 'a';
            }
        }
        elapsedTime = System.nanoTime() - beginTime;
        System.out.println("Elapsed Time is " + elapsedTime/1000 + "usec (Build String)");
        String strReverse = "";

        /*
        用String做反转
         */
        beginTime = System.nanoTime();
        for (int pos = str.length() - 1; pos >= 0; pos--) {
            strReverse += str.charAt(pos);
        }
        elapsedTime = System.nanoTime() - beginTime;
        System.out.println("Elapsed Time is " + elapsedTime/1000 + "usec (Using String to reverse)");

        /*
        用StringBuffer做反转
         */
        beginTime = System.nanoTime();
        StringBuffer sBufferReverse = new StringBuffer(size);
        for (int pos = str.length() - 1; pos >= 0; pos--) {
            sBufferReverse.append(str.charAt(pos));
        }
        elapsedTime = System.nanoTime() - beginTime;
        System.out.println("Elapsed Time is " + elapsedTime/1000 + "usec (Using StringBuffer to reverse)");
        beginTime = System.nanoTime();
        StringBuffer sBufferReverseMethod = new StringBuffer(str);
        sBufferReverseMethod.reverse();
        elapsedTime = System.nanoTime() - beginTime;
        System.out.println("Elapsed Time is " + elapsedTime/1000 + "usec (Using StringBuffer's reverse() method)");

        /*
        用StringBuilder做反转
         */
        beginTime = System.nanoTime();
        StringBuilder sBuilderReverse = new StringBuilder(size);
        for (int pos = str.length() - 1; pos >= 0; pos--) {
            sBuilderReverse.append(str.charAt(pos));
        }
        elapsedTime = System.nanoTime() - beginTime;
        System.out.println("Elapsed Time is " + elapsedTime/1000 + "usec (Using StringBuilder to reverse)");
        beginTime = System.nanoTime();
        StringBuilder sBuilderReverseMethod = new StringBuilder(str);
        sBuilderReverseMethod.reverse();
        elapsedTime = System.nanoTime() - beginTime;
        System.out.println("Elapsed Time is " + elapsedTime/1000 + "usec (Using StringBuilder's reverse() method)");
    }
}
